package com.yunxiao.cloud.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @description: HostUtil
 * @author: yunxiao
 * @date: 2020/2/21 9:01
 * @version: V1.0
 **/
public class HostUtil {
    private static Logger logger = LoggerFactory.getLogger(HostUtil.class);

    private HostUtil() {
        //do nothing
    }

    /**
     * 获取本机IP地址
     *
     * @return
     */
    public static String getLocalHost() {
        String ipAddress = "";
        Enumeration allNetInterfaces = null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();

            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip instanceof Inet4Address) {
                        ipAddress = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("getLocalHost error:", e);
        }

        return ipAddress;
    }
}
